package com.jiaoyou.baojian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jiaoyou.baojian.BaojianApplication;
import com.jiaoyou.baojian.R;
import com.jiaoyou.baojian.adapter.GiftAdapter;
import com.jiaoyou.baojian.adapter.MessageAdapter;
import com.jiaoyou.baojian.agora.AgoraHelper;
import com.jiaoyou.baojian.agora.ChannelAttr;
import com.jiaoyou.baojian.agora.ChannelMsg;
import com.jiaoyou.baojian.dialog.YesOrNoDialog;
import com.jiaoyou.baojian.entity.GiftEntity;
import com.jiaoyou.baojian.entity.LocalMessageEntity;
import com.jiaoyou.baojian.entity.MessageEntity;
import com.jiaoyou.baojian.entity.RoomEntity;
import com.jiaoyou.baojian.entity.UserDetail;
import com.jiaoyou.baojian.entity.UserInfo;
import com.jiaoyou.baojian.entity.response.ChargeResponse;
import com.jiaoyou.baojian.entity.response.RoomItemResponse;
import com.jiaoyou.baojian.http.Api;
import com.jiaoyou.baojian.http.BaofangCallback;
import com.jiaoyou.baojian.http.BaofangCallback2;
import com.jiaoyou.baojian.http.response.BaseResponse;
import com.jiaoyou.baojian.otto.Event;
import com.jiaoyou.baojian.utils.Utils;
import com.squareup.otto.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

import static io.agora.rtc.Constants.CHANNEL_PROFILE_COMMUNICATION;

public class TalkingActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {

    @BindView(R.id.avatar)
    ImageView avatar;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.time)
    Chronometer time;
    @BindView(R.id.handsfree)
    ImageView handsfree;
    @BindView(R.id.mute)
    ImageView mute;
    @BindView(R.id.quit)
    ImageView quit;
    @BindView(R.id.linearLayout4)
    LinearLayout linearLayout4;
    @BindView(R.id.msg_list)
    RecyclerView msgList;
    @BindView(R.id.gift_list)
    RecyclerView gifts;

    private List<GiftEntity> giftList;
    private GiftAdapter giftAdapter;
    private MessageAdapter messageAdapter;
    private List<MessageEntity> messageList;

    private boolean isHandsfree = false;
    private boolean isMute = false;
    private boolean isZhubo = false;

    private String channelName;
    private String channelKey;

    private UserInfo userInfo;
    private RoomItemResponse roomItemResponse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        channelName = getIntent().getStringExtra("channel_name");
        channelKey = getIntent().getStringExtra("channel_key");
        isZhubo = getIntent().getBooleanExtra("actress", false);
        userInfo = (UserInfo) getIntent().getSerializableExtra("userInfo");
        Serializable serializable = getIntent().getSerializableExtra("room");
        if(serializable != null)
            roomItemResponse = (RoomItemResponse) serializable;

        enterTalking();
        fillData();

        time.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                ////每30秒心跳一次
                String time = chronometer.getText().toString();
                if (":50".equals(time.substring(time.lastIndexOf(":")))) {
                    checkOrCharge();
                }
                if (":01".equals(time.substring(time.lastIndexOf(":"))))
                    heartBeat();
                if (":15".equals(time.substring(time.lastIndexOf(":"))))
                    heartBeat();
                if (":30".equals(time.substring(time.lastIndexOf(":"))))
                    heartBeat();
                if (":45".equals(time.substring(time.lastIndexOf(":"))))
                    heartBeat();
            }
        });
        time.start();

        needOtto();

        isCallBusy = true;

        BaojianApplication.getInstance().pushService.clearNotifications();
    }

    private void addMsg(int id, LocalMessageEntity localMessageEntity) {
        boolean isMine = (id == getLoginResponse().user.id);
        MessageEntity messageEntity = new MessageEntity();
        switch(localMessageEntity.type) {
            case 2: {
                String username = localMessageEntity.name;
                String avatar = localMessageEntity.avatar;
                int giftid = localMessageEntity.gift_id;
                messageEntity.msg = (isMine ? "你" : username) + "送了一个" + Utils.getGiftNameFromGiftList(giftid, giftList);
                messageEntity.type = 2;
                messageEntity.avatar = avatar;
                messageList.add(messageEntity);
                messageAdapter.notifyDataSetChanged();
                msgList.smoothScrollToPosition(messageList.size());
                Utils.showGiftAnimation(this, giftid, giftList);
            }
            break;
            case 1:
            case 3: {
                String username = localMessageEntity.name;
                String avatar = localMessageEntity.avatar;
                String content = localMessageEntity.content;
                messageEntity.type = 1;
                messageEntity.msg = content;
                messageEntity.username = username;
                messageEntity.avatar = avatar;
                messageList.add(messageEntity);
                messageAdapter.notifyDataSetChanged();
                msgList.smoothScrollToPosition(messageList.size());
            }
            break;
        }
    }

    private void checkOrCharge() {
        if (isZhubo)
            charge();
        else
            check();
    }

    //检查余额
    private void check() {
        Api.getInstance().checkCard(new BaofangCallback<ChargeResponse>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                finish();
                toast("通话出错：" + t.getLocalizedMessage());
            }

            @Override
            public void onSuccess(ChargeResponse chargeResponse) {
                int remainTime = remainTime(chargeResponse);
                if (remainTime == 2) {
                    showYesOrNoDialog("余额不足，2分钟后自动挂断", "取消", "充值", new YesOrNoDialog.OnClickListener() {
                        @Override
                        public void onLeftClick() {

                        }

                        @Override
                        public void onRightClick() {
                            RechargeActivity.show(TalkingActivity.this);
                        }
                    });
                    return;
                }
                if (remainTime == 1) {
                    showYesOrNoDialog("余额不足，1分钟后自动挂断", "取消", "充值", new YesOrNoDialog.OnClickListener() {
                        @Override
                        public void onLeftClick() {

                        }

                        @Override
                        public void onRightClick() {
                            RechargeActivity.show(TalkingActivity.this);
                        }
                    });
                    return;
                }
                if (remainTime == 0) {
                    toastFullscreen("余额不足，\n通话自动结束");
                    AgoraHelper.getInstance().agoraAPI.channelInviteEnd(channelName, userInfo.id + "", 0);
                    onBackPressed();
                    return;
                }
            }
        });
    }

    //扣费
    private void charge() {
        Api.getInstance().actressCharge(new BaofangCallback<ChargeResponse>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                finish();
                toast("通话出错：" + t.getLocalizedMessage());
            }

            @Override
            public void onSuccess(ChargeResponse chargeResponse) {
                int remainTime = remainTime(chargeResponse);
                if (remainTime == 2) {
                    toastFullscreen("对方仅剩两分钟通话时间，\n快提醒用户充值吧");
                    return;
                }
                if (remainTime == 1) {
                    toastFullscreen("对方仅剩一分钟通话时间，\n快提醒用户充值吧");
                    return;
                }
                if (remainTime == 0) {
                    toastFullscreen("对方余额不足，\n通话自动结束");
                    AgoraHelper.getInstance().agoraAPI.channelInviteEnd(channelName, userInfo.id + "", 0);
                    onBackPressed();
                    return;
                }
            }
        });
    }

    //检查客户的余额还能通话多久
    private int remainTime(ChargeResponse chargeResponse) {
        int yue = chargeResponse.callerCard.getTotalAmount();
        int candyPerMin = chargeResponse.callingRoom.candyPerMin;
        if (candyPerMin == 0) {
            candyPerMin = 1;
        }
        return yue / candyPerMin;
    }

    private void fillData() {
        name.setText(userInfo.nickname);
        Utils.showCircleImage(this, userInfo.avatar, avatar);

        messageList = new ArrayList<>();
        messageAdapter = new MessageAdapter();
        msgList.setLayoutManager(new LinearLayoutManager(this));
        msgList.setAdapter(messageAdapter);
        messageAdapter.setNewData(messageList);
        messageAdapter.setEmptyView(getMsgEmptyView());
        messageAdapter.notifyDataSetChanged();

        giftList = new ArrayList<>();
        giftAdapter = new GiftAdapter();
        LinearLayoutManager giftLinearLayoutManager = new LinearLayoutManager(this);
        giftLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        gifts.setLayoutManager(giftLinearLayoutManager);
        gifts.setAdapter(giftAdapter);
        giftAdapter.setNewData(giftList);
        giftAdapter.setEmptyView(getEmptyView());
        giftAdapter.notifyDataSetChanged();
        giftAdapter.setOnItemClickListener(this);

        Api.getInstance().getGiftList(new BaofangCallback2<GiftEntity>() {

            @Override
            public void onFailure(Call<BaseResponse<GiftEntity>> call, Throwable t) {

            }

            @Override
            public void onSuccess(List<GiftEntity> giftEntities) {
                giftList.addAll(giftEntities);
                giftAdapter.notifyDataSetChanged();
            }
        });

        if (isZhubo) {
            gifts.setVisibility(View.GONE);
        }
    }

    private View getMsgEmptyView(){
        TextView textView = new TextView(this);
        textView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(getResources().getColor(R.color.main_gray));
        textView.setText("土豪们送的礼物会在这里显示哦~");
        return textView;
    }

    private View getEmptyView() {
        TextView textView = new TextView(this);
        textView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        textView.setGravity(Gravity.CENTER);
        textView.setText("加载中");
        return textView;
    }

    @Override
    public int getContentView() {
        return R.layout.activity_talking;
    }

    /**
     * 进入对话
     */
    private void enterTalking() {
        AgoraHelper.getInstance().agoraAPI.channelJoin(channelName);
        if(roomItemResponse != null && roomItemResponse.room != null) {
            AgoraHelper.getInstance().agoraAPI.channelSetAttr(channelName, "roomId", roomItemResponse.room.id + "");
        }
        rtcEngine.setChannelProfile(CHANNEL_PROFILE_COMMUNICATION);
        rtcEngine.enableAudio();
        rtcEngine.joinChannel(channelKey, channelName, "", getLoginResponse().user.id);
        rtcEngine.setEnableSpeakerphone(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        time.stop();
        rtcEngine.leaveChannel();
        AgoraHelper.getInstance().agoraAPI.channelLeave(channelName);
        //退出
        if(isZhubo) {
            Api.getInstance().exitP2PRoom(new BaofangCallback<String>() {
                @Override
                public void onFailure(Call call, Throwable t) {

                }

                @Override
                public void onSuccess(String s) {
                    Log.e("exitP2PRoom", "" + s);
                }
            });
        } else {
            Api.getInstance().hangup(new BaofangCallback<String>() {
                @Override
                public void onFailure(Call call, Throwable t) {

                }

                @Override
                public void onSuccess(String s) {
                    Log.e("exitP2PRoom", "" + s);
                }
            });
        }
        //刷新个人信息
        Api.getInstance().getUserDetail(getLoginResponse().user.id, new BaofangCallback<UserDetail>() {
            @Override
            public void onFailure(Call call, Throwable t) {

            }

            @Override
            public void onSuccess(UserDetail userDetail) {
                getLoginResponse().update(TalkingActivity.this, userDetail);
            }
        });

        isCallBusy = false;
    }

    @OnClick({R.id.avatar, R.id.name, R.id.handsfree, R.id.mute, R.id.quit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.avatar:
            case R.id.name:
                Intent intent = new Intent(this, UserInfoActivity.class);
                UserInfo userInfo = new UserInfo();
                intent.putExtra("userinfo", userInfo);
                startActivity(intent);
                break;
            case R.id.handsfree:
                if (isHandsfree) {
                    isHandsfree = false;
                    rtcEngine.setEnableSpeakerphone(false);
                    handsfree.setImageResource(R.drawable.btn_handsfree_off);
                } else {
                    isHandsfree = true;
                    rtcEngine.setEnableSpeakerphone(true);
                    handsfree.setImageResource(R.drawable.btn_handsfree_on);
                }
                break;
            case R.id.mute:
                if (isMute) {
                    isMute = false;
                    rtcEngine.muteAllRemoteAudioStreams(false);
                    mute.setImageResource(R.drawable.btn_mute_off);
                } else {
                    isMute = true;
                    rtcEngine.muteAllRemoteAudioStreams(true);
                    mute.setImageResource(R.drawable.btn_mute_on);
                }
                break;
            case R.id.quit:
                onBackPressed();
                break;
        }
    }

    @Subscribe
    public void onEvent(String event) {
        if (event.equals(Event.AGORA_CHANNEL_USER_LEAVED)) {
            toast("通话结束");
            finish();
        }
    }

    @Subscribe
    public void onEvent(Event event){
        if(event.event.equals(Event.AGORA_MSG_CHANNEL_RECEIVE)){
            ChannelMsg channelMsg = getGson().fromJson(event.content, ChannelMsg.class);
            if(channelMsg.channelId.equals(channelName)) {
                LocalMessageEntity localMessageEntity = getGson().fromJson(channelMsg.msg, LocalMessageEntity.class);
                addMsg(localMessageEntity.uid, localMessageEntity);
            }
        } else if(event.event.equals(Event.AGORA_CHANNEL_ATTR_CHANGED)){
            if(roomItemResponse != null)
                return;
            ChannelAttr channelAttr = getGson().fromJson(event.content, ChannelAttr.class);
            if(channelAttr.channelId.equals(channelName)){
                if(channelAttr.key.equals("roomId"))
                {
                    roomItemResponse = new RoomItemResponse();
                    roomItemResponse.room = new RoomEntity();
                    roomItemResponse.room.id = Integer.parseInt(channelAttr.value);
                }
            }
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        final GiftEntity giftEntity = giftList.get(position);
        showYesOrNoDialog("赠送礼物" + giftEntity.getDescription(), "取消", "赠送", new YesOrNoDialog.OnClickListener() {
            @Override
            public void onLeftClick() {
            }

            @Override
            public void onRightClick() {
                final LocalMessageEntity localMessageEntity = LocalMessageEntity.giveGift(getLoginResponse().user.id, getLoginResponse().userInfo.nickname, getLoginResponse().userInfo.avatar, giftEntity.getId(), giftEntity.getImg(), giftEntity.getDescription());
                Api.getInstance().giveGift(userInfo.userId, giftEntity.getId(), 1, new BaofangCallback() {
                    @Override
                    public void onFailure(Call call, Throwable t) {
                        toast("余额不足，请充值");
                        showYesOrNoDialog("余额不足，请充值", "取消", "充值", new YesOrNoDialog.OnClickListener() {
                            @Override
                            public void onLeftClick() {

                            }

                            @Override
                            public void onRightClick() {
                                RechargeActivity.show(TalkingActivity.this);
                            }
                        });
                    }

                    @Override
                    public void onSuccess(Object o) {
//                        addMsg(getLoginResponse().user.id, localMessageEntity);
                        AgoraHelper.getInstance().agoraAPI.messageChannelSend(channelName, getGson().toJson(localMessageEntity), "");
                    }
                });
            }
        });
    }

    @Override
    public void onBackPressed() {
        showYesOrNoDialog("确定退出通话？", new YesOrNoDialog.OnClickListener(){
            @Override
            public void onLeftClick() {

            }

            @Override
            public void onRightClick() {
                TalkingActivity.super.onBackPressed();
            }
        });
    }

    public void heartBeat() {
        if(roomItemResponse == null || roomItemResponse.room == null)
            return;
        if(isZhubo){
            Api.getInstance().roomHeartbeatZhubo(roomItemResponse.room.id, new BaofangCallback<Integer>() {
                @Override
                public void onFailure(Call call, Throwable t) {
                    toast("包房出错：" + t.getLocalizedMessage());
                    finish();
                }

                @Override
                public void onSuccess(Integer o) {

                }
            });
        } else {
            Api.getInstance().roomUserHeartbeat(roomItemResponse.room.id, new BaofangCallback<Integer>() {
                @Override
                public void onFailure(Call call, Throwable t) {
                    toast("包房出错：" + t.getLocalizedMessage());
                    finish();
                }

                @Override
                public void onSuccess(Integer o) {

                }
            });
        }
    }
}
